/**
 * Created by jiachenpan on 16/11/18.
 */

export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (('' + time).length === 10) time = parseInt(time) * 1000
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1]
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

export function formatTime(time, option) {
  time = +time * 1000
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) { // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return d.getMonth() + 1 + '月' + d.getDate() + '日' + d.getHours() + '时' + d.getMinutes() + '分'
  }
}

// 深拷贝
export const deepcopy = function(source) {
  if (!source) {
    return source
  }
  const sourceCopy = source instanceof Array ? [] : {}
  for (const item in source) {
    sourceCopy[item] = typeof source[item] === 'object' ? deepcopy(source[item]) : source[item]
  }
  return sourceCopy
}

// 得到路由
export const GetDiffRoutes = function(addRouters, visitedRouters) {
  var result = []
  var flag = false

  for (var i = 0; i < addRouters.length; i++) {
    var obj = addRouters[i]
    flag = false
    for (var j = 0; j < visitedRouters.length; j++) {
      var aj = visitedRouters[j]
      if (obj.path === aj.path) {
        flag = true
        break
      }
    }
    if (!flag) {
      result.push(obj)
    }
  }

  return result
}

/**
 * 解析url参数
 * @example ?id=12345&a=b
 * @return Object {id:12345,a:b}
 */
export const urlParse = function(urls) {
  const url = urls || window.location.search
  const obj = {}
  const reg = /[?&][^?&]+=[^?&]+/g
  const arr = url.match(reg)
  // ['?id=12345', '&a=b']
  if (arr) {
    arr.forEach((item) => {
      const tempArr = item.substring(1).split('=')
      const key = decodeURIComponent(tempArr[0])
      const val = decodeURIComponent(tempArr[1])
      obj[key] = val
    })
  }
  return obj
}

// 查找匹配的路由
export const matchPath = function(router, path) {
  let isMatched = false
  var replayResult = []
  findRoutePath(replayResult, router)
  if (Array.isArray(replayResult) && replayResult.length >= 0) {
    if (replayResult.some(v => v === path)) {
      isMatched = true
    }
  }
  return isMatched
}

function findRoutePath(replayResult, array, base) {
  array.forEach(function(route) {
    let pathKey = (base || '') + route.path
    replayResult.push(pathKey)
    if (Array.isArray(route.children)) {
      pathKey = route.path + (base || '/')
      findRoutePath(replayResult, route.children, pathKey)
    }
  })
}

/**
 * @param server 服务地址
 * @param api 对应的api
 * @param params 查询参数
 * @return 返回拼接处理好的 excel下载地址url
*/
export function splitDownloadExcelUrl(server, api, params) {
  const now_server = server
  const now_api = api
  const now_params = params
  let wUrl = ''
  let itemStr = ''
  for (const i in now_params) {
    if (now_params[i] === null || now_params[i] === undefined) {
      now_params[i] = ''
    }
    if (now_params[i] !== '') {
      itemStr = [i] + '=' + now_params[i]
      itemStr = itemStr + '&'
      wUrl += itemStr
    }
  }
  if (wUrl === '') {
    return now_server + now_api
  } else {
    // 清除末尾 多余的 '&'
    const reg = /&$/gi
    const cUrl = wUrl.replace(reg, '')
    return now_server + now_api + '?' + cUrl
  }
}

/**
 * @param a:[1,2,3,5,10]
 * @param b:[1,2]
 * @return a = [3,5,10]
 */
export function array_diff(a, b) {
  for (let i = 0; i < b.length; i++) {
    for (let j = 0; j < a.length; j++) {
      if (a[j] === b[i]) {
        a.splice(j, 1)
        j = j - 1
      }
    }
  }
  return a
}

/**
 * 前提数组内的item 必须有唯一标识参数idKey,例：id
 * 引用 import * as Utils from '@/utils/index'
 * 使用 const new_arr = Utils.array_cut_item(arr, item, idKey) // 减去数组内某对象
 * @param arr [{ id:1, num:11 }, { id:2, num:12}, { id:3, num:13}]
 * @param item { id:1, num:11 }
 * @param idKey 'id'
 * @return arr [{ id:2, num:12}, { id:3, num:13}]
 */
export function array_cut_item(arr, item, idKey) {
  for (let j = 0; j < arr.length; j++) {
    if (arr[j][idKey] === item[idKey]) {
      arr.splice(j, 1)
    }
  }
  return arr
}

/**
 * 判断合法对象
 * 不是一个空对象，且不是未定义对象，且不等于空字符串
 * @param obj
 * @return true 合法对象/ false 非法对象
 */
export function isLegalObject(obj) {
  const x = obj
  if (x === null || x === undefined || x === '') {
    return false
  } else {
    return true
  }
}

/**
 * 引用 import * as Utils from '@/utils/index'
 * 使用 const allAmountOne = Utils.sumFunc(a, 'num') // 计算总数
 * @param data: [{ id:1, num:11 }, { id:2, num:12}, { id:3, num:13}]
 * @param val: 'num' 需要用于计算的参数
 * @return now_sum: 11 + 12 + 13 = 36
 */
export function sumFunc(data, val) {
  let res_sum = 0
  if (data && data.length > 0) {
    for (let c = 0; c < data.length; c++) {
      let now_num = 0
      if (data[c][val]) { // data[c][val] 预防值为null undefined '' 等情况
        now_num = +parseFloat(data[c][val]).toFixed(2)
      }
      res_sum += now_num
      res_sum = +res_sum.toFixed(2)
    }
  } else {
    res_sum = 0
  }
  return res_sum
}

/**
 * 前提数组内的item 必须有唯一标识参数idKey,例：id
 * 引用 import * as Utils from '@/utils/index'
 * 使用 const new_arr = Utils.addArrayFunc(arr1, arr2, idKey) // 合并数组
 * @param arr1: [{ id:1, num:11 }, { id:2, num:12}, { id:3, num:13}]
 * @param arr2: [{ id:2, num:11 }, { id:3, num:13}, { id:4, num:14}]
 * @param idKey 'id'
 * @return res_arr: [ { id:1, num:11 }, { id:2, num:11 }, { id:3, num:13}, { id:4, num:14}]
 */
export function addArrayFunc(arr1, arr2, idKey) {
  const init_arr = arr1.concat(arr2)
  const res_arr = []
  for (let i = 0; i < init_arr.length; i++) {
    // 如果当前数组的第i已经保存进了临时数组，那么跳过，
    // 否则把当前项push到临时数组里面
    if (res_arr.length === 0) {
      res_arr.push(init_arr[i])
    } else {
      let repeat = false
      for (let c = 0; c < res_arr.length; c++) {
        if (res_arr[c][idKey] === init_arr[i][idKey]) {
          repeat = true
        }
      }
      if (!repeat) {
        res_arr.push(init_arr[i])
      }
    }
  }
  return res_arr
}

/**
 * 引用 import * as Utils from '@/utils/index'
 * 使用 const new_arr = Utils.tableAddOptions(arr1, options) // 数组内每个对象添加自定义属性
 * @param arr1: [{ id:1, num:11 }, { id:2, num:12}, { id:3, num:13}]
 * @param options: 'nowAddPrice'
 * @return res_arr: [{ id:1, num:11, nowAddPrice: '' }, { id:2, num:12, nowAddPrice: ''}, { id:3, num:13, nowAddPrice: ''}]
 */
export function tableAddOptions(arr1, options) {
  for (let i = 0; i < arr1.length; i++) {
    arr1[i][options] = ''
  }
  return arr1
}

// 星期几
export function currentWeek(num) {
  let add_num = 0
  if (num) {
    add_num = parseInt(num)
  }
  const a = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
  const week = (new Date().getDay() + add_num) % 7
  return a[week]
}

/**
 * @param time 必传 时间戳
 * @param num 非必传 临时调整增加日期天数
 * @return 星期几
 */
export function currentWeekWithTime(time, num) {
  let add_num = 0
  if (num) {
    add_num = parseInt(num)
  }
  const a = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
  const week = (new Date(time).getDay() + add_num) % 7
  return a[week]
}

/**
 * 引用 import * as Utils from '@/utils/index'
 * 使用 const now_table_data = Utils.excelLabel2tableParam(excelData, execlHeader, tableContent)
 * @param excelData 表格的主体数据 [{ '账户编号': '112', '总数量': '11'}, { '账户编号': '113', '总数量': '12'}]
 * @param excelHeader 表格的表头数据 ["账户编号", "总数量", "车型编码", "车型名称", "起运地", "运单状态", "目的地", __ob__: Observer]
 * @param tableContent excel转换成table的参数对照表 [{ prop: 'billCode', label: '账户编号' },{ prop: 'num', label: '总数量' }]
 * @param callback 回调返回处理后的用于table显示的数据 [{ billCode: '112', num: '11' }, { billCode: '113', num: '12'}]
 */
export function excelLabel2tableParam(excelData, excelHeader, tableContent, callback) {
  const arr1 = excelData
  const arr2 = excelHeader
  const arr3 = tableContent
  let now_item = {}
  const new_arr = []
  for (let c = 0; c < arr1.length; c++) {
    now_item = excelLabel2tableParamItem(c, arr1, arr2, arr3)
    delete now_item.myLisaId
    new_arr.push(now_item)
  }
  callback(new_arr)
}
function excelLabel2tableParamItem(index, excelData, excelHeader, tableContent) {
  const arr1 = excelData
  const arr2 = excelHeader
  const arr3 = tableContent
  const itemOne = {}
  const res_arr = []
  const j = index
  const arr1Item = arr1[j]
  itemOne.myLisaId = j
  for (const k in arr3) {
    if (arr2.indexOf(arr3[k].label) !== -1) {
      // console.log('arr1[j][arr3[k].label]', arr1[j][arr3[k].label])
      if (arr1Item[arr3[k].label]) {
        itemOne[arr3[k].prop] = arr1[j][arr3[k].label]
      } else {
        itemOne[arr3[k].prop] = null
      }
    }
  }
  if (j === 0) {
    return itemOne
  } else {
    let repeat = false
    for (let y = 0; y < res_arr.length; y++) {
      if (itemOne.myLisaId === res_arr[j].myLisaId) {
        repeat = true
      }
    }
    if (!repeat) {
      return itemOne
    }
  }
}

// sessionStorage
export const session = function(key, value) {
  if (value === void (0)) {
    var lsVal = sessionStorage.getItem(key)
    if (lsVal && lsVal.indexOf('autostringify-') === 0) {
      return JSON.parse(lsVal.split('autostringify-')[1])
    } else {
      return lsVal
    }
  } else {
    if (typeof (value) === 'object' || Array.isArray(value)) {
      value = 'autostringify-' + JSON.stringify(value)
    }
    return sessionStorage.setItem(key, value)
  }
}

/**
 * 引用 import * as Utils from '@/utils/index'
 * 使用 const new_arr = Utils.removalRepeat(String, Array) // 值添加进数组，去重复
 * @param String '22'
 * @param Array ['22', '11', '33']
 * @return Array ['22', '11', '33']
 */
export function removalRepeat(String, Array) {
  let repeat = false
  for (let y = 0; y < Array.length; y++) {
    if (String === Array[y]) {
      repeat = true
    }
  }
  if (!repeat) {
    Array.push(String)
  }
  return Array
}

/** 数字金额大写转换(可以处理整数,小数,负数) */
export function smallToBIG(n) {
  var fraction = ['角', '分']
  var digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
  var unit = [['元', '万', '亿'], ['', '拾', '佰', '仟']]
  var head
  if (n < 0) {
    head = '欠'
  } else {
    head = ''
  }
  n = Math.abs(n)

  var s = ''

  for (var i = 0; i < fraction.length; i++) {
    s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '')
  }
  s = s || '整'
  n = Math.floor(n)

  for (var c = 0; c < unit[0].length && n > 0; c++) {
    var p = ''
    for (var j = 0; j < unit[1].length && n > 0; j++) {
      p = digit[n % 10] + unit[1][j] + p
      n = Math.floor(n / 10)
    }
    s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][c] + s
  }
  return head + s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/, '零元整')
}

/**
 * 引用 import * as Utils from '@/utils/index'
 * 使用 const new_boolean = Utils.hasPermissions(array,item,idKey) // 判断数集内是否有该对象，有则返回 true，无则返回false
 * @param array  [{ id:1, num:11 }, { id:2, num:12}, { id:3, num:13}]
 * @param item  { id:1, num:11 }
 * @param idKey 'id'
 * @return true/false
 */
export function hasPermissions(array, item, idKey) {
  if (item && item[idKey]) {
    return array.some(row => item[idKey] === row[idKey])
  } else {
    return true
  }
}

/**
 * 将以base64的图片url数据转换为Blob
 * @param urlData
 * 用url方式表示的base64图片数据
 */
export function convertBase64UrlToBlob(urlData) {
  const arr = urlData.split(',')
  const mime = arr[0].match(/:(.*?);/)[1]
  const bstr = atob(arr[1])
  let n = bstr.length
  const u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new Blob([u8arr], { type: mime })
}

/**
 * 对象数组去重
 * */
export function arrayUnique2(arr, name) {
  const hash = {}
  return arr.reduce(function(item, next) {
    hash[next[name]] ? '' : hash[next[name]] = true && item.push(next)
    return item
  }, [])
}

/**
 *  检查值 是否是 数字规则, 保留小数点后4位
 * */
export function ratioEndWithFour(value) {
  const numberReg = new RegExp('^\\d{1,3}$|^\\d{1,3}[.]\\d{1,4}$')
  let c = false
  if (numberReg.test(value)) {
    c = true
  } else {
    c = false
  }
  return c
}
